package InterfaceClient;


import java.awt.Component;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;

import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.Icon;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.filechooser.FileSystemView;


public class JDriveCombo extends javax.swing.JComboBox {

	private static final long serialVersionUID = 1L;
	private JLocationList lists = null;
	private JComboBox me = null;
	private ComboBoxModel model = null;

	public JDriveCombo(JLocationList lists) {
		super();
		me = this;
		this.lists = lists;
		initGUI(lists);
	}

        

	public JLocationList getLists() {
		return lists;
	}

	private void initGUI(final JLocationList lists) {
		try {
			{
				model = new DefaultComboBoxModel(File.listRoots());
				this.setModel(model);
				this.setPreferredSize(new java.awt.Dimension(174, 23));
				this.setRenderer(new MyComboBoxRenderer());
				lists.setParentFile(me.getSelectedItem().toString());
				this.addPopupMenuListener(new PopupMenuListener() {
					public void popupMenuWillBecomeVisible(PopupMenuEvent evt) {
						refresh();
					}
					public void popupMenuWillBecomeInvisible(PopupMenuEvent evt) {
					}
					public void popupMenuCanceled(PopupMenuEvent evt) {
					}
				});
				this.addItemListener(new ItemListener() {
					public void itemStateChanged(ItemEvent evt) {
						if(lists!=null){
							lists.setParentFile(me.getSelectedItem().toString());
						}
					}
				});
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	protected void refresh() {
		String selectedValue = (me.getSelectedItem()!=null)? me.getSelectedItem().toString():"";
		model = new DefaultComboBoxModel(File.listRoots());
		me.setModel(model);
		model.setSelectedItem(selectedValue);
	}
	
	class MyComboBoxRenderer extends JLabel implements ListCellRenderer {

		private static final long serialVersionUID = 1L;

		public MyComboBoxRenderer(){
			setOpaque(true);
		}

		public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {

			if (isSelected) {
				setBackground(list.getSelectionBackground());
				setForeground(list.getSelectionForeground());
			} else {
				setBackground(list.getBackground());
				setForeground(list.getForeground());
			}

			setText(value.toString());
			FileSystemView view = FileSystemView.getFileSystemView();      
			Icon theIcon = view.getSystemIcon(new File(value.toString()));
			setIcon(theIcon);

			return this;
		}
	}
}


